//
//  PhoneLoginViewController.m
//  帮惠Mall
//
//  Created by reew on 2017/9/14.
//  Copyright © 2017年 reew. All rights reserved.
//

#import "PhoneLoginViewController.h"
#import <AFNetworking.h>
#import "Login.h"
#import "CommonUtils.h"
#import <SVProgressHUD.h>
#import "Account.h"
#import "System.h"
@interface PhoneLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UIButton *codeLoginBtn;
@property (nonatomic,strong) UILabel *leftView;
@property (nonatomic,strong) UIButton *rightView;
@property (nonatomic) BOOL isPasswordLogin;
@property (weak, nonatomic) IBOutlet UIButton *changeTypeBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (nonatomic,strong) NSString *adminNo;
@end
NSTimer *timer;
static int timeValue = 60;
@implementation PhoneLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isPasswordLogin = YES;
    [self setUpView];
    self.navigationController.navigationBarHidden = YES;
}

- (void) setUpView{
    _changeTypeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //设置label的左视图
    UILabel *leftLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 45)];
    leftLabel1.text = @"手机号";
    leftLabel1.font = [UIFont systemFontOfSize:18];
    _phoneNumber.leftViewMode = UITextFieldViewModeAlways;
    _phoneNumber.leftView = leftLabel1;
    _phoneNumber.text = _phone;
    
    _leftView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 45)];
    _leftView.text = @"密码";
    _leftView.font = [UIFont systemFontOfSize:18];
    _password.leftViewMode = UITextFieldViewModeAlways;
    _password.leftView  = _leftView;
    
    _rightView = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightView.frame = CGRectMake(0, 0, 80, 26);
    _rightView.backgroundColor = [UIColor whiteColor];
    _rightView.layer.borderColor = [UIColor grayColor].CGColor;
    [_rightView.layer setMasksToBounds:YES];
    [_rightView.layer setBorderWidth:1];
    [_rightView setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_rightView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _rightView.titleLabel.font = [UIFont systemFontOfSize:12];
    _rightView.layer.cornerRadius = 10;
    _rightView.clipsToBounds = YES;
    _password.rightView = _rightView;
    [_rightView addTarget:self action:@selector(getCode_admin) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}


- (void)getCode_admin{
    //判断手机号是否正确
    if ([CommonUtils isPhoneNum:_phoneNumber.text]) {
        //初始化timer
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];
        //网络请求验证码
        AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
        NSString *url = [kBaseURL stringByAppendingPathComponent:kGetCodeLogin_admin];
        [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //传入的参数
            NSData *data = [_phoneNumber.text dataUsingEncoding:NSUTF8StringEncoding];
            [formData appendPartWithFormData:data name:@"account"];
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功返回
            NSString *message = responseObject[@"message"];
            [SVProgressHUD showInfoWithStatus:message];
            _adminNo = responseObject[@"adminNo"];
            NSLog(@"%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败，提示
            [CommonUtils showHudWithStatus:ErrorStatus stayTime:1 info:@"网络错误"];
            NSLog(@"%@",error);
        }];
    }else{
        //提示手机号码错误，请输入正确的手机号
        [CommonUtils showHudWithStatus:ErrorStatus stayTime:1 info:@"请输入正确的手机号码"];
    }
    
}
//倒计时
- (void)dealYzmBut{
    
    if (timeValue == 0) {
        [_rightView setBackgroundColor:[UIColor colorWithRed:53/255.0 green:163/255.0 blue:223/255.0 alpha:1]];
        [_rightView setTitle:@"重新发送" forState:0];
        _rightView.userInteractionEnabled = YES;
        timeValue = 60;
        [timer invalidate];
        return;
    }
    
    [_rightView setBackgroundColor:[UIColor lightGrayColor]];
    _rightView.userInteractionEnabled = NO;
    [_rightView setTitle:[NSString stringWithFormat:@"%ds",timeValue] forState:0];
    timeValue--;
}
//登录
///密码登录

- (void)passwordLogin_admin{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
    NSString *url = [kBaseURL stringByAppendingPathComponent:kPasswordLogin_admin];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //参数：手机号：account  密码：passwd
        [formData appendPartWithFormData:[_phoneNumber.text dataUsingEncoding:NSUTF8StringEncoding] name:@"account"];
        [formData appendPartWithFormData:[_password.text dataUsingEncoding:NSUTF8StringEncoding] name:@"passwd"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        NSNumber *status = responseObject[@"result"];
        NSString *message = responseObject[@"message"];
        if ([status integerValue] == 0) {
            [SVProgressHUD showErrorWithStatus:message];
        }else{
            //登录成功后的操作
            [SVProgressHUD setMaximumDismissTimeInterval:0.5];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            //保存登录信息
            [self saveInfo:responseObject[@"data"][@"mallAdmin"]];
            [self showHomeView];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
        [SVProgressHUD setMaximumDismissTimeInterval:1];
        [self showHomeView];
    }];
}
///验证码登录

- (void)authCodeLogin_admin{
    AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
    NSString *urlStr = [kBaseURL stringByAppendingPathComponent:kCodeLogin_admin];;
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //参数：手机号：account，验证码：mobileNumber
        [formData appendPartWithFormData:[_phoneNumber.text dataUsingEncoding:NSUTF8StringEncoding] name:@"account"];
        [formData appendPartWithFormData:[_password.text dataUsingEncoding:NSUTF8StringEncoding] name:@"mobileNumber"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功：
        NSNumber *status = responseObject[@"result"];
        NSString *message = responseObject[@"message"];
        if ([status integerValue] == 1) {
            //登录成功
            [SVProgressHUD setMaximumDismissTimeInterval:0.5];
            [SVProgressHUD showSuccessWithStatus:message];
            //登录成功的操作
            [self saveInfo:responseObject[@"data"][@"mallAdmin"]];
            [self showHomeView];
        }else{
            [SVProgressHUD showErrorWithStatus:message];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        [SVProgressHUD showErrorWithStatus:@"网络连接失败"];
    }];
}

- (void)showHomeView{
    UITabBarController *vc = [CommonUtils getHomeVC];
    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
}
- (void)saveInfo:(NSDictionary *)responseObject{

    [[Account sharedAccount] saveLoginInfo:responseObject];
}
- (IBAction)login:(UIButton *)sender {
    
    if (_isPasswordLogin) {
        //密码登录
        [self passwordLogin_admin];

    }else{
        //验证码登录
        [self authCodeLogin_admin];
    }
}
//左上角返回
- (IBAction)close:(UIButton *)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
//更改登录方式
- (IBAction)changeLoginType:(UIButton *)sender {
    if (_isPasswordLogin) {
        _leftView.text = @"验证码";
        _password.rightViewMode = UITextFieldViewModeAlways;
        _isPasswordLogin = NO;
        [_changeTypeBtn setTitle:@"密码登录" forState:UIControlStateNormal];
    }else{
        _leftView.text = @"密码";
        _password.rightViewMode = UITextFieldViewModeNever;
        _isPasswordLogin = YES;
        [_changeTypeBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.phoneNumber resignFirstResponder];
    [self.password resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
